package com.lines.chap02;

/**
 * <p>
 * <code>MyArray</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-23 11:13
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class MyArray {

    //数据的长度
    private int size;
    private int data[];
    //当前已经存的数据大小
    private int index;//仅仅是为了用于判断是否需要扩容的

    public MyArray(int size) {
        this.size = size;
        this.data = new int[size];
        this.index = 0;
    }

    public void print(){
        System.out.println("index:"+index);
        for (int i = 0; i < size; i++) {
            System.out.print(data[i]+" ");
        }
        System.out.println();
    }

    public void insert(int loc,int n){
        if (index++<size){
            //找到数组最后一位，假设数组最后一位坐标是4，loc是2
            /*
            [4] = [3]
            [3] = [2]

            2此时就就可以直接赋值
            */
            for (int i = size-1; i >loc ; i--) {
                data[i] = data[i-1];
            }
            data[loc] = n;
        }else {
            //扩容
            size = size * 2;
            data = new int[size];
        }
    }

    public void delete(int loc){
        for (int i = loc; i <size; i++) {
            if (i!=size-1){
                data[i] = data[i+1];
            }else {
                data[i] = 0;
            }
        }
        index--;
    }

    public void update(int loc,int n){
        data[loc] = n;
    }

    public int get(int loc){
        return data[loc];
    }


    public static void main(String[] args) {
        MyArray myArray = new MyArray(5);
        myArray.insert(0,8);
        myArray.insert(1,30);
        myArray.insert(2,12);
        myArray.insert(3,21);
        myArray.print();
        System.out.println("==============");
        myArray.insert(2,90);
        myArray.print();
        System.out.println("==============");
        myArray.delete(2);
        myArray.print();
        System.out.println("==============");
    }
}
